package com.sn.author.filter.aop;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sn.author.domain.BaseResult;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author Xiaoming
 * @Date 2019/9/11 16:13
 * @Version 1.0.0
 **/
@Aspect
@Component
public class LogAspect {

    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(*  *.*.*.controller..*.*(..))")
    public void controllerMethod() {
    }

    @Before("controllerMethod()")
    public void logRequestInfo(JoinPoint joinPoint) throws Exception {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();


        StringBuilder requestLog = new StringBuilder();
        requestLog.append("【请求信息】：")
                .append(" \n -> URL \t = {")
                .append(request.getRequestURI())
                .append("},\n")
                .append(" -> 请求方式 = {")
                .append(request.getMethod()).append("},\n")
                .append(" -> 请求IP\t = {").append(request.getRemoteAddr())
                .append("},\n").append(" -> 访问方法 = {")
                .append(joinPoint.getSignature().getDeclaringTypeName())
                .append(".").append(joinPoint.getSignature().getName()).append("},\n");

        if (joinPoint.getArgs().length == 0) {
            requestLog.append(" -> 访问参数 = {} ");
        } else {
            try {
                requestLog.append(" -> 访问参数 = ").append(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)
                        .writeValueAsString(joinPoint.getArgs()[0]));
            }catch (Exception ignored){}
        }

        logger.info(requestLog.toString());
    }


    @AfterReturning(returning = "result", pointcut = "controllerMethod()")
    public void logResultInfo(BaseResult<Object> result) throws Exception {
        String json = JSONObject.toJSONString(result);
        if (StringUtils.isNotEmpty(json) && json.length() > 500) {
            json = json.substring(0, 400) + "......";
        }
        logger.info("【请求结果】：" + json);
    }

}
